<script setup>
import { ref, onMounted, reactive } from 'vue'
import request from '@/utils/sj-request'
import { ElMessage, ElMessageBox } from 'element-plus'

// 用户列表数据
const userList = ref([])
// 搜索关键词
const searchKeyword = ref('')
// 加载状态
const loading = ref(false)
// 分页参数
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 角色列表
const roleList = ref([])

// 选中的角色
const selectedRole = ref('')

// 对话框显示控制
const dialogVisible = ref(false)
const dialogTitle = ref('新增用户')

// 表单数据
const userForm = reactive({
  id: null,
  account: '',
  password: '',
  email: '',
  roleId: null
})

// 表单校验规则
const rules = {
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 4, max: 20, message: '账号长度必须在4-20个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度必须在6-20个字符之间', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ],
  roleId: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 表单引用
const formRef = ref(null)

// 获取角色列表
const fetchRoles = async () => {
  try {
    const res = await request({
      url: '/role/list',
      method: 'get'
    })
    if (res.code === 200) {
      const allowedRoles = ["管理员", "学科组长", "教师"];
      roleList.value = (res.data || []).filter(item => allowedRoles.includes(item.name));

    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  }
}

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true
  try {
    const res = await request({
      url: '/user-management/page',
      method: 'get',
      params: {
        page: pagination.value.currentPage,
        size: pagination.value.pageSize,
        keyword: searchKeyword.value,
        roleId: selectedRole.value || null
      }
    })
    
    if (res.code === 200) {
      userList.value = res.data.records || []
      pagination.value.total = res.data.total || 0
    } else {
      ElMessage.error(res.message || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 处理页码变化
const handleCurrentChange = (page) => {
  pagination.value.currentPage = page
  fetchUsers()
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  pagination.value.pageSize = size
  pagination.value.currentPage = 1
  fetchUsers()
}

// 处理搜索
const handleSearch = () => {
  pagination.value.currentPage = 1
  fetchUsers()
}

// 处理重置筛选条件
const handleReset = () => {
  searchKeyword.value = ''
  selectedRole.value = ''
  pagination.value.currentPage = 1
  fetchUsers()
}

// 格式化用户状态
const formatUserStatus = (status) => {
  return status === 1 ? { type: 'success', label: '正常' } : { type: 'danger', label: '禁用' }
}

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''
  const date = new Date(dateTimeStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 打开新增用户对话框
const handleAdd = () => {
  dialogTitle.value = '新增用户'
  // 重置表单
  userForm.id = null
  userForm.account = ''
  userForm.password = ''
  userForm.email = ''
  userForm.roleId = null
  
  // 显示对话框
  dialogVisible.value = true
}

// 打开编辑用户对话框
const handleEdit = (row) => {
  dialogTitle.value = '编辑用户'
  // 填充表单数据
  userForm.id = row.id
  userForm.account = row.account
  userForm.password = '' // 编辑时不需要填写密码
  userForm.email = row.email
  userForm.roleId = row.roleId
  
  // 显示对话框
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const isEdit = userForm.id !== null
        const url = isEdit ? '/user-management' : '/user-management'
        const method = isEdit ? 'put' : 'post'
        
        // 编辑时不需要提交密码字段
        const submitData = { ...userForm }
        if (isEdit) {
          delete submitData.password
        }
        
        const res = await request({
          url,
          method,
          data: submitData
        })
        
        if (res.code === 200) {
          ElMessage.success(isEdit ? '编辑成功' : '新增成功')
          dialogVisible.value = false
          fetchUsers()
        } else {
          ElMessage.error(res.message || (isEdit ? '编辑失败' : '新增失败'))
        }
      } catch (error) {
        console.error(isEdit ? '编辑用户失败:' : '新增用户失败:', error)
        ElMessage.error(isEdit ? '编辑失败' : '新增失败')
      }
    }
  })
}

// 切换用户状态
const toggleUserStatus = (row) => {
  // 管理员用户不能被禁用
  if (row.roleName === '管理员') {
    ElMessage.warning('不能修改管理员状态')
    return
  }
  
  const action = row.status === 1 ? '禁用' : '启用'
  ElMessageBox.confirm(`确定要${action}该用户吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 实际项目中应该调用后端API
      // 这里假设后端有一个切换状态的接口
      // const res = await request({
      //   url: `/user-management/status/${row.id}/${row.status === 1 ? 0 : 1}`,
      //   method: 'put'
      // })
      
      // 模拟成功响应
      row.status = row.status === 1 ? 0 : 1
      ElMessage.success(`${action}成功`)
    } catch (error) {
      console.error(`${action}用户失败:`, error)
      ElMessage.error(`${action}失败`)
    }
  }).catch(() => {
    // 取消操作
  })
}

// 删除用户
const handleDelete = (id, roleName) => {
  // 管理员用户不能被删除
  if (roleName === '管理员') {
    ElMessage.warning('不能删除管理员用户')
    return
  }
  
  ElMessageBox.confirm('确定要删除该用户吗？删除后不可恢复！', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await request({
        url: `/user-management/${id}`,
        method: 'delete'
      })
      
      if (res.code === 200) {
        ElMessage.success('删除成功')
        fetchUsers()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      console.error('删除用户失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 判断是否为管理员用户
const isAdmin = (roleName) => {
  return roleName === '管理员'
}

// 组件挂载时获取数据
onMounted(() => {
  fetchRoles()
  fetchUsers()
})
</script>

<template>
  <div class="user-container">
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-container" shadow="never">
      <el-form :inline="true" class="filter-form">
        <el-form-item label="关键词">
          <el-input
            v-model="searchKeyword"
            placeholder="用户名/姓名/邮箱/手机"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        
        <el-form-item 
        style="width: 15%;" label="角色">
          <el-select v-model="selectedRole" placeholder="选择角色" clearable>
            <el-option
              v-for="role in roleList"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 用户列表 -->
    <el-card class="list-container" shadow="never">
      <template #header>
        <div class="card-header">
          <span>用户列表</span>
          <el-button type="primary" @click="handleAdd">新增用户</el-button>
        </div>
      </template>
      
      <el-table
        v-loading="loading"
        :data="userList"
        border
        style="width: 100%"
      >
        <el-table-column label="序号" width="80">
          <template #default="{$index}">
            {{ (pagination.currentPage - 1) * pagination.pageSize + $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="account" label="账号" width="120" />
        <el-table-column prop="email" label="邮箱" show-overflow-tooltip />
        <el-table-column prop="roleName" label="角色" width="100" />
        
        <el-table-column label="更新时间" width="180">
          <template #default="{row}">
            {{ formatDateTime(row.updated_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{row}">
            <el-button 
              link 
              type="primary" 
              size="small" 
              @click="handleEdit(row)"
              :disabled="isAdmin(row.roleName)"
            >
              编辑
            </el-button>
            
            <el-button 
              link 
              type="danger" 
              size="small" 
              @click="handleDelete(row.id, row.roleName)"
              :disabled="isAdmin(row.roleName)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="userForm"
        :rules="rules"
        label-width="80px"
        status-icon
      >
        <el-form-item label="账号" prop="account">
          <el-input v-model="userForm.account" placeholder="请输入账号" />
        </el-form-item>
        
        <el-form-item label="密码" prop="password" v-if="!userForm.id">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="userForm.roleId" placeholder="请选择角色" style="width: 100%">
            <el-option
              v-for="role in roleList"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.user-container {
  padding: 20px 0;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.list-container {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>